//
//  SLPreferencesSetVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/23.
//

#import "SLLockLogVC.h"
#import "SLLockLogCell.h"
#import "SLLogWarnAlertView.h"
#import "SLLogDeleteAlertView.h"
static  NSString *const kCellId = @"SLLockLogCell";

@interface SLLockLogVC ()<UITableViewDelegate,UITableViewDataSource>{
    BOOL _isFirstLoad;
}
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, assign) NSInteger uploadCount;
@property (nonatomic, strong) NSArray *openLogs;
@property (nonatomic, strong) NSArray *warnLogs;
@end

@implementation SLLockLogVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpSubViews];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newWarnRefreshLogVc) name:@"kWarnRefreshLogVc" object:nil];
    [ZCTool showLoadingOnKeyWindow];
    [self loadData:NO];
    _isFirstLoad = YES;
}

-(void)newWarnRefreshLogVc{
    [self showWarnAlertView];
    [self loadData:NO];
}

-(void)backBtnClicked{
    [super backBtnClicked];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)loadData:(BOOL)isSysnc{
    kWeakSelf(self);
    NSDictionary *params = @{@"page":@(1),
                             @"pageSize":@(999),
                             @"deviceId":kCurClickDevice.deviceId};
    
    [ZKHttpManager getWithPath:@"/msl_lock_key/UnlockLog/list" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        [weakself.tableView endRefresh];
        if (isSuccessed == NO){
            kShowToast(message);
            [weakself refreshSubViews];
            return;
        }
        if (isSysnc) {
            kShowToast(@"Log update successful.");
        }
        NSArray *data = [[NSArray alloc] initWithArray:result[@"result"][@"items"]];
        self->_dataArray = [NSMutableArray new];
        //更新数据源
        [data enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
            SLLockLogModel *model = [SLLockLogModel modelWithDictionary:dict];
            [weakself.dataArray addObject:model];
        }];
        [self groupUnlockItemsByDate:weakself.dataArray];
        [weakself refreshSubViews];
        
        if (self->_isFirstLoad) {
            self->_isFirstLoad = NO;
            [self syncLogDataBackground];
        }
        if ([self->_model.isHaveNewWarn isEqualToString:@"1"]) {
            [self showWarnAlertView];
        }
    }];
}

-(void)groupUnlockItemsByDate:(NSArray<SLLockLogModel *> *)items {
    NSMutableDictionary<NSString *, NSMutableArray<SLLockLogModel *> *> *groupedItems = [NSMutableDictionary dictionary];

    // 遍历每个 UnlockItem，按日期分组
    for (SLLockLogModel *item in items) {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[item.unlockTime intValue]];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSString *dateString = [dateFormatter stringFromDate:date];
        // 将 UnlockItem 添加到相应日期的数组中
        if (!groupedItems[dateString]) {
            groupedItems[dateString] = [NSMutableArray array];
        }
        [groupedItems[dateString] addObject:item];
    }
    
    // 将字典转换为二维数组，并按时间倒序排序
    NSMutableArray *resultArray = [NSMutableArray array];
    
    // 按日期倒序遍历
    NSArray *sortedDateKeys = [[groupedItems allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *date1, NSString *date2) {
        return [date2 compare:date1 options:NSOrderedDescending];
    }];
    
    for (NSString *dateKey in sortedDateKeys) {
        // 获取当前日期组
        NSMutableArray<SLLockLogModel *> *itemsForDate = groupedItems[dateKey];
        // 按 unlockTime 倒序排序
        [itemsForDate sortUsingComparator:^NSComparisonResult(SLLockLogModel *obj1, SLLockLogModel *obj2) {
            return [obj1.unlockTime intValue] < [obj2.unlockTime intValue] ? NSOrderedDescending : NSOrderedAscending;
        }];
        // 添加到结果数组
        [resultArray addObject:itemsForDate];
    }
    _dataArray = [resultArray copy];
}

-(void)showWarnAlertView{
    if (![[ZCTool getCurrentUIVC] isKindOfClass:[SLLockLogVC class]]) {
        return;
    }
    NSInteger warnType = [_model.lastWarnType integerValue];
    if (warnType == 0 || warnType == 1 || warnType == 2 || warnType == 7 || warnType == 8) {
        __weak SLLogWarnAlertView *alert = [kAppWindow viewWithTag:10999];
        if (alert) return;
        alert = [SLLogWarnAlertView viewFromXIB];
        alert.warnType = [_model.lastWarnType integerValue];
        [alert setBtnBlock:^(NSInteger btnIndex) {
            [ZKHttpManager sysncDeviceDataWith:@{@"isHaveNewWarn":@"0"} finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
                if (isSuccessed) {
                    kNotifyRefreshDevcieList;
                    self->_model.isHaveNewWarn = @"0";
                }
            }];
        }];
        alert.tag = 10999;
        [kAppWindow addSubview:alert];
    }
}

-(void)setUpSubViews{
    self.title = _model.deviceName;
    [self addNavigationItemWithImageNames:@[@"icon_delete"] isLeft:NO target:self action:@selector(deleteLog) tags:@[@"1000"]];
    [self.bgView addSubview:self.tableView];
    UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 15)];
    head.backgroundColor = KClearColor;
    _tableView.tableHeaderView = head;
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.right.offset(-20);
        make.top.bottom.offset(0);
    }];
    
    _sureBtn.btnStyle = 1;
}

-(void)deleteLog{
    SLLogDeleteAlertView *selectView = [SLLogDeleteAlertView viewFromXIB];
    [selectView showWithAnmation:self.view];
    kWeakSelf(self);
    [selectView setBtnBlock:^(NSInteger btnIndex) {
        [weakself deleteLogWith:btnIndex];
    }];
}

-(void)deleteLogWith:(NSInteger)index{
    if (_dataArray.count == 0) {
        return;
    }
    NSDate *date = [NSDate date];
    NSString *startTime = @"";
    NSString *endTime = [NSString dateStrFromDate:[date dateByAddingDays:1] formatStr:@"yyyy-MM-dd"];
    if (index == 1) {//一天
        startTime = [NSString dateStrFromDate:date formatStr:@"yyyy-MM-dd"];
        
    }else if (index == 2){//一周
        startTime = [NSString dateStrFromDate:[date dateByAddingWeeks:-1] formatStr:@"yyyy-MM-dd"];
    }else if (index == 3){//一月
        startTime = [NSString dateStrFromDate:[date dateByAddingMonths:-1] formatStr:@"yyyy-MM-dd"];
    }else if (index == 4){//全部
        endTime = @"";
        startTime = @"";
    }
    NSDictionary *params = @{@"deviceId":kCurClickDevice.deviceId,
                             @"deviceNo":kCurClickDevice.deviceNo,
                             @"startTime":startTime,
                             @"endTime":endTime};
    [ZCTool showLoadingOnKeyWindow];
    [ZKHttpManager deleteWithPath:@"/msl_lock_key/UnlockLog/BatchDelete" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        if (isSuccessed == NO){
            [ZCTool hideLoadingOnKeyWindow];
            kShowToast(message);
            return;
        }
        [self loadData:NO];
        kNotifyRefreshDevcieList;
    }];
}

#pragma mark -
#pragma mark - ================<同步日志数据>===============
- (IBAction)sureAction:(id)sender {
    [ZCTool showLoadingOnKeyWindow];
    [self syncLogData];
}

-(void)syncLogData{
    [ZCTool connectDeviceWith:kCurClickDevice toast:kLocalString(@"Connecting...") finish:^(BOOL isSuccess) {
        if (!isSuccess) {
            [ZCTool hideLoadingOnKeyWindow];
            return;
        }
        [ZCTool batchSyncDeviceOpenLogDatas:^(BOOL isSuccess, NSString * _Nonnull message) {
            if (!isSuccess) {
                kShowToast(message);
                [ZCTool hideLoadingOnKeyWindow];
                return;
            }
            [self loadData:YES];
        }];
    }];
}

-(void)syncLogDataBackground{
    [ZCTool connectDeviceBackgroundWith:kCurClickDevice finish:^(BOOL isSuccess) {
        if (!isSuccess) {
            return;
        }
        [ZCTool batchSyncDeviceOpenLogDatas:^(BOOL isSuccess, NSString * _Nonnull message) {
            if (!isSuccess) {
                return;
            }
            [self loadData:NO];
        }];
    }];
}

-(void)refreshSubViews{
    if (_dataArray.count == 0) {
        [ZCTool showDefaultImageOnView:self.tableView];
    }else{
        [ZCTool hideDefaultImageOnView:self.tableView];
    }
    [_tableView reloadData];
}


#pragma mark - ================<tableViewDataSource>===============
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *sectionArr = _dataArray[section];
    return sectionArr.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SLLockLogCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    SLLockLogModel *model = _dataArray[indexPath.section][indexPath.row];
    NSArray *section = _dataArray[indexPath.section];
    cell.upLine.hidden = indexPath.row == 0;
    cell.downLine.hidden = indexPath.row == section.count-1;
    cell.model = model;
    
    [cell.contentView setRoundedCorners:0 forCorners:UIRectCornerAllCorners frame:CGRectMake(0, 0, kScreenWidth-40, 50)];
    if (indexPath.row == section.count-1) {
        [cell.contentView setRoundedCorners:20.0 forCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight frame:CGRectMake(0, 0, kScreenWidth-40, 65)];
    }
    return cell;
}

#pragma mark - ================<UITableViewDelegate>===============
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *section = _dataArray[indexPath.section];
    if (indexPath.row == section.count - 1) {
        return 65;
    }
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 25;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *headview = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    UILabel *label = [headview viewWithTag:100];
    if (!headview) {
        headview = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"head"];
        headview.frame = CGRectMake(0, 0, kScreenWidth, 60);
        headview.contentView.backgroundColor = KBgColor_2;
        [headview setRoundedCorners:20.0 forCorners:UIRectCornerTopLeft | UIRectCornerTopRight frame:CGRectMake(0, 0, kScreenWidth-40, 60)];
        if (!label) {
            label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, kScreenWidth-80, 15)];
            label.textColor =  KWhiteColor_text;
            label.font = kFontBold(16);
            label.tag = 100;
            [headview addSubview:label];
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 49.5, self.tableView.width, 0.5)];
            line.backgroundColor = kHexColor(@"#343434");
            [headview addSubview:line];
        }
    }
    SLLockLogModel *model = _dataArray[section][0];
    label.text = [NSString timeStringFromTimestamp:model.unlockTime formart:@"MMM. d, yyyy"];
    return headview;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"foot"];
        footerView.frame = CGRectMake(0, 0, kScreenWidth, 25);
        footerView.contentView.backgroundColor = KClearColor;
    }
    return footerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
   
}


#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 55;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:kCellId bundle:nil] forCellReuseIdentifier:kCellId];
        _tableView.backgroundColor = KClearColor;
        _tableView.showsVerticalScrollIndicator = NO;
    }
    return _tableView;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}



@end
